import { mallApi } from '/api/mall'
import { userApi } from '/api/user'
import { checkAuth, getUser } from '/store/actions'
import { checkUserisVip, getServer, isLogin } from '/store/mutations'
// import { taskApi } from '/api/task'
import { GlobalData } from '/store/state'
import { $event, $logger, $utils } from '/utils'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    info: {} as DomoCommodity,

    commentFocus: false,
    inputValue: '',
    replyUser: 0,
    /** 键盘弹起高度 */
    keyboardOffsetTop: 0,

    loading: true,
    access: {},
    shareImage: '',
    share: false,
    interval: 4000,
    duration: 500,
    rechargeRatio: 0,
    /** 抵扣积分 */
    scoreNumber: 0,
    userScore: 0,
    scrollTop: false,
    follower: false,
    scrollClass: false,
    height: GlobalData.clientHeihgt - GlobalData.navigationHeight,
    navigationHeight: GlobalData.navigationHeight,
    currentTab: 0,
    navScrollLeft: 0,
    list: [] as DomoFeed[],
    noMore: false,
    collect: false,
    closable: false,
    query: {} as any,
    currencyName: GlobalData.currencyName,
    menuTop: 0,
    productInfo: {} as DomoCommodity,
    buyer: [],
    setTime: '' as any,
    num: 0,
    showpic: null as any,
    hidepic: null as any,
    mall_commodities: {} as DomoCommodity,
    mineId: 0,
    isAdmin: false,
    vip: GlobalData.vip,
    user: {} as DomoUser,
    /** 规格弹窗显示 */
    optionsShow: false,
    options: '',
    /** 加入购物车锁 */
    carts: false,
    showConfirm: false,
    orderId: 0,
    qrCodeShow: false,
    /** 是否有库存，默认有 */
    hasExtra: true,
    /** 选中的规格 */
    sku: {},
    skuIndex: 0,
    countPrice: 0,
    cartsCount: 0,
    previewType: 'image',
    swiperIndex: 0,
  },
  onLoad(query: any) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
    })
    let commodityId = +query.commodityId ? +query.commodityId : +query.id
    if (!commodityId && query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      commodityId = scene.commodityId ? +scene.commodityId : +scene.id
    }
    query.orderId &&
      this.setData({
        orderId: +query.orderId,
      })
    try {
      if (!commodityId) throw new Error('该商品不存在或已被删除')
      this.setData({
        loading: false,
      })
      this.getProductInfo(commodityId)
    } catch (error) {
      $logger.debug('商品详情加载失败', { query, error })
      wx.navigateBack({ delta: 1 })
      return
    }
    this.showBuyer()
    $event.on('after:boot', this, () => {
      this.getPostition()
    })
    $event.on('logged', this, () => {
      this.getUserId()
    })
    this.getPostition()
  },
  async onShow() {
    const token = wx.getStorageSync(`${getServer()}/accessToken`).data
    if (token) {
      wx.nextTick(() => {
        this.getUserId()
      })
    } else {
      await checkAuth()
    }
  },
  getPostition() {
    this.setData({
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      rechargeRatio: GlobalData.currency.settings['recharge-ratio'],
      vip: GlobalData.vip,
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      path: $utils.getSharePath(),
    }
  },
  onShareTimeline() {
    console.log($utils.getSharePath())

    return {
      title: this.data.info.title,
      imageUrl: this.data.info.photos[0].image.url,
      path: $utils.getSharePath(),
    }
  },
  onPageScroll() {
    this.fixedProductTitle()
    this.fixedTitle()
  },
  /** 判断是否滚动到了点评 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#fixedTitle').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] ? res[0].top < 1 + this.data.navigationHeight : true,
      })
    })
  },
  /** 判断是否滚动到了商品名字 */
  fixedProductTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].top < 1 + this.data.navigationHeight : true,
      })
    })
  },
  onDownload() {
    $event.emit('download')
  },
  async onfollower() {
    await checkAuth()
    const mineId = this.getUserId()
    if (+mineId === +this.data.info.user_id) return
    //关注锁
    if (this.data.follower) return
    const userId = this.data.info.user_id
    this.setData({
      follower: true,
    })
    if (this.data.info.user.has_follower) {
      await userApi.unFollowUser(userId)
      this.setData({
        [`info.user.has_follower`]: false,
      })
      wx.showToast({ title: '已取消关注', icon: 'success' })
    } else {
      await userApi.followUser(userId)
      this.setData({
        [`info.user.has_follower`]: true,
      })
      wx.showToast({ title: '关注成功', icon: 'success' })
    }
    this.setData({
      follower: false,
    })
  },
  async getProductInfo(commodityId: any) {
    /** 有没有库存 */
    let {
      data: { hasExtra },
    } = this
    const productInfo = await mallApi.getCommodityDetail(commodityId, { width: 'shopInfo' })
    const excludes = wx.getStorageSync(`${getServer()}/logged`).data
    const userScore = excludes ? excludes.currency.sum : 0
    /** 兼容之前发布的商品 */
    productInfo.type = productInfo.type == 'ticket' ? productInfo.type : 'normal'
    let buyer = []
    try {
      buyer = await mallApi.getProductBarrage(commodityId)
      buyer.splice(productInfo.orders_count)
    } catch (error) {
      console.log('没有购买记录')
    }

    /** 遍历商品规格库存 */
    if (productInfo.sku && productInfo.sku.length > 0) {
      hasExtra = productInfo.sku.some((i: any) => {
        return i.inventory > 0
      })
    }
    productInfo.userPrice = productInfo.market_price

    // 视频放第一位置。兼容旧数据
    for (let i = 0; i < productInfo.photos.length; i++) {
      if (productInfo.photos[i].video) {
        productInfo.photos = [productInfo.photos[i], ...productInfo.photos] as any
        productInfo.photos.splice(i + 1, 1)
        break
      }
    }

    this.setData({
      hasExtra,
      info: productInfo,
      productInfo,
      mall_commodities: productInfo,
      scoreNumber: productInfo.score > userScore ? userScore : productInfo.score,
      userScore,
      buyer,
      previewType:
        productInfo.photos.length >= 1 && productInfo.photos[0].video ? 'video' : 'image',
    })
  },
  // tab切换
  clickTab(e: any) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false
    } else {
      this.setData({ currentTab: e.target.dataset.current })
      this.switchList()
    }
    return false
  },
  async switchList() {
    const cur = this.data.currentTab
    if (cur === 0 || this.data.list.length > 0) return
    const commodityId = this.data.info.id
    const list = await mallApi.getCommodityCommodities(commodityId)
    const noMore = list.length < 15
    this.setData({
      list,
      noMore,
    })
  },
  async onLoadmore() {
    if (this.data.noMore) {
      wx.showToast({
        icon: 'none',
        title: '已没有更多',
      })
      return
    }
    wx.showLoading({ title: '加载中' })
    const offset = this.data.list.length
    const commodityId = this.data.info.id
    const list = await mallApi.getCommodityCommodities(commodityId, { offset, limit: 15 })
    const noMore = list.length < 15
    this.setData({
      list: [...this.data.list, ...list],
      noMore,
    })
    wx.hideLoading()
  },
  onReset() {
    /** 评论列表上划事件 */
  },
  async onCollect() {
    await checkAuth()
    if (this.data.collect) return
    if (this.checkCommondityDown()) {
      return
    }
    const commodityId = this.data.info.id
    this.setData({
      collect: true,
    })
    if (this.data.info.liked) {
      await mallApi.unCollectCommodities(commodityId)
      this.setData({
        [`info.liked`]: false,
      })
      wx.showToast({ title: '已取消收藏', icon: 'success' })
    } else {
      await mallApi.collectCommodities(commodityId)
      this.setData({
        [`info.liked`]: true,
      })
      wx.showToast({ title: '收藏成功', icon: 'success' })
    }
    this.setData({
      collect: false,
    })
  },
  async toPay(event: WechatMiniprogram.CustomEvent) {
    if (!isLogin()) {
      await checkAuth()
    }
    /** isOrig===1为原价，反之折扣 */
    const commodityId = this.data.info.id
    const data = event.currentTarget.dataset
    wx.navigateTo({
      url: `/mall/pay/pay?commodityId=${commodityId}&orig=${data.isorig}`,
    })
  },
  /** 获取登录用户的ID */
  getUserId() {
    const abilities: any = GlobalData.userAbilities
    const isAdmin = abilities && abilities.some((i: any) => i.name === 'mall:admin')
    const user = wx.getStorageSync(`${getServer()}/logged`).data
    this.getCarts()
    if (user.vip) {
      user.vip.isVip = checkUserisVip(user)
    }
    this.setData({
      isAdmin,
      mineId: user.id,
      user,
    })
    return user.id
  },
  /** 购物车商品数量 */
  async getCarts() {
    const carts = await mallApi.getCartsCount()
    this.setData({
      cartsCount: carts.count,
    })
  },
  async publish() {
    this.publishCommentDebounce(this)
  },
  publishCommentDebounce: $utils.debounce((that: any) => {
    that.publishComment()
  }, 200),
  async publishComment() {
    await checkAuth()
    const {
      data: { orderId },
    } = this
    await this.getProductInfo(this.data.info.id)
    if (this.data.info.can_comment) {
      wx.showActionSheet({
        itemList: ['文字', '图片', '视频'],
        success(res) {
          switch (res.tapIndex) {
            case 0:
              wx.navigateTo({
                url: `/pages/publish/publish?about=mall_commodities&orderId=${orderId}`,
              })
              break

            case 1:
              wx.navigateTo({
                url: `/pages/publish/publish?type=image&about=mall_commodities&orderId=${orderId}`,
              })
              break
            case 2:
              wx.navigateTo({
                url: `/pages/publish/publish?type=video&about=mall_commodities&orderId=${orderId}`,
              })
              break
          }
        },
      })
    } else {
      wx.showActionSheet({
        itemColor: '#999',
        itemList: ['下单后才能点评，一个订单只能点评一次'],
      })
    }
  },
  //开会员
  toVip() {
    wx.navigateTo({
      url: '/mine/vip/vip',
    })
  },
  /** 气氛弹窗 */
  showBuyer() {
    const _this = this
    let num = _this.data.num
    const animation = wx.createAnimation({}) //创建一个动画实例
    _this.setData({
      //创建一个计时器
      setTime: setInterval(function () {
        _this.setData({
          num: num++,
        })

        if (num > _this.data.buyer.length) {
          num = 0
        }

        animation.opacity(1).step({
          duration: 1000,
        })
        setTimeout(() => {
          _this.setData({
            showpic: animation.export(),
          })
        }, 500)

        animation.opacity(0).step({ duration: 1000 })
        _this.setData({ hidepic: animation.export() })
      }, 4000),
    })
  },
  /** 编辑 */
  editor() {
    const itemList: any[] = []
    const {
      data: { mineId, info },
    } = this
    const abilities: any = GlobalData.userAbilities
    const isAdmin = abilities && abilities.some((i: any) => i.name === 'mall:admin')
    if (isAdmin || +mineId === +info.user.id) {
      itemList.push('删除')
      itemList.push(info.deleted_at ? '上架' : '下架')
    }
    if (+mineId === +info.user.id) {
      itemList.push('编辑')
    }
    if (isAdmin) {
      itemList.push(info.topped_at !== undefined ? '取消全局置顶' : '全局置顶')
      itemList.push(info.category_topped_at !== undefined ? '取消分类置顶' : '分类置顶')
    }
    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        switch (itemList[res.tapIndex]) {
          case '编辑':
            wx.navigateTo({
              url: `/mall/publish/publish?edit=true`,
            })
            break
          case '下架':
            mallApi
              .rackUpOrDownProduct(info.id, true)
              .then(() => {
                info.deleted_at = Date().toString()
                this.setData({ info })
                $event.emit('shopDownStateUpdate', info)
                wx.showToast({
                  title: '下架成功',
                })
              })
              .catch((error) => {
                const {
                  data: { message = '操作失败' },
                } = error
                wx.showToast({
                  title: message,
                  icon: 'none',
                })
              })

            break
          case '上架':
            mallApi
              .rackUpOrDownProduct(info.id, false)
              .then(() => {
                info.deleted_at = null
                this.setData({ info })
                $event.emit('shopDownStateUpdate', info)
                wx.showToast({
                  title: '上架成功',
                })
              })
              .catch((error) => {
                const {
                  data: { message = '操作失败' },
                } = error
                wx.showToast({
                  title: message,
                  icon: 'none',
                })
              })

            break
          case '删除':
            mallApi
              .deleteProduct(info.id)
              .then(() => {
                wx.showToast({
                  title: '删除成功',
                })
                setTimeout(() => {
                  const pages = getCurrentPages()
                  if (pages.length === 1) {
                    wx.switchTab({ url: '/pages/feed/list/list' })
                  } else {
                    wx.navigateBack({ delta: 1 })
                  }
                }, 1000)
              })
              .catch((error) => {
                const {
                  data: { message = '删除失败' },
                } = error

                wx.showToast({
                  title: message,
                  icon: 'none',
                })
              })
            break
          case '分类置顶':
            this.toToped('分类置顶')
            break
          case '全局置顶':
            this.toToped('全局置顶')
            break
          case '取消分类置顶':
            this.toToped('取消分类置顶')
            break
          case '取消全局置顶':
            this.toToped('取消全局置顶')
            break
        }
      },
    })
  },
  /** 置顶操作 */
  toToped(name: string) {
    const {
      data: { info },
    } = this
    const datas =
      name === '分类置顶'
        ? { category_topped: true }
        : name === '取消分类置顶'
        ? { category_topped: false }
        : name === '全局置顶'
        ? { topped: true }
        : { topped: false }
    mallApi
      .editorProduct(info.id, datas)
      .then((res) => {
        this.setData({
          info: res,
        })
      })
      .catch(() => {
        wx.showToast({
          title: '操作失败',
          icon: 'none',
        })
      })
  },
  /** 加入购物车提示 */
  async joinCart() {
    if (!isLogin()) {
      await checkAuth()
    }
    const {
      data: {
        info: { buying_read },
      },
    } = this
    if (buying_read) {
      this.setData({ showConfirm: true })
    } else {
      this.chooseCart()
    }
  },
  /** 关闭弹窗 */
  closeConfirm() {
    this.setData({ showConfirm: false })
  },
  /** 加入购物车 */
  joinCarts() {
    const {
      data: {
        info: { id, order_min_qty },
        options,
        carts,
      },
    } = this
    this.closeConfirm()
    if (carts) return
    this.setData({
      carts: true,
    })
    const data = {
      commodity_id: id,
      quantity: order_min_qty ? order_min_qty : 1,
    } as any
    if (options) {
      data.commodity_option = options
    }
    mallApi
      .joinCarts(data)
      .then(() => {
        wx.showToast({
          title: '加入购物车成功',
        })
        this.setData({
          carts: false,
        })
        $event.emit('change:payCarts')
      })
      .catch(() => {
        wx.showToast({
          title: '加入购物车失败',
          icon: 'none',
        })
        this.setData({
          carts: false,
        })
      })
  },
  /** 选择规格 */
  chooseCart() {
    const {
      data: {
        info: { sku },
      },
    } = this
    this.closeConfirm()
    if (sku && sku.length > 0) {
      return this.openOptions()
    }
    this.joinCarts()
  },
  /** 打开选择规格弹窗 */
  openOptions() {
    const {
      data: { info, options, sku, user },
    } = this
    let {
      data: { countPrice },
    } = this
    if (!countPrice) {
      countPrice = +info.market_price + info.sku[0].extra
      if (user.vip && user.vip.isVip) {
        countPrice = +info.extra[`${user.vip.level}`] + info.sku[0].extra
      }
    }
    this.setData({
      optionsShow: true,
      options: options ? options : info.sku[0].name,
      sku: sku ? sku : info.sku[0],
      countPrice,
    })
  },
  close() {
    this.setData({
      optionsShow: false,
    })
  },
  /** 选择规格 */
  chooseOptions(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item, index },
      },
    } = e
    const {
      data: { info, user },
    } = this
    let countPrice = +info.market_price + item.extra
    if (user.vip && user.vip.isVip) {
      countPrice = +info.extra[`${user.vip.level}`] + item.extra
    }
    this.setData({ options: item.name, sku: item, skuIndex: index, countPrice })
  },
  /** 确定 */
  beSure() {
    if (!this.data.options) {
      wx.showToast({
        title: '请选择商品规格',
        icon: 'none',
      })
      return
    }
    this.close()
    this.joinCarts()
  },
  /**
   *
   * @returns true 商品已经下架了
   */
  checkCommondityDown() {
    const {
      data: { info },
    } = this
    if (info.deleted_at) {
      wx.showToast({
        title: '该商品已下架',
        icon: 'none',
      })
      return true
    }
    return false
  },
  /** 跳转聊天 */
  toChat() {
    const {
      data: { info },
    } = this
    if (Object.keys(info).length == 0) {
      return
    }
    if (this.checkCommondityDown()) {
      return
    }
    const my = GlobalData.imVersion + getUser().id
    const nameList = {
      myName: my,
      your: GlobalData.imVersion + info.user_id,
      name: getUser().name,
      yourname: info.user ? info.user.name : '未知用户',
    }
    wx.navigateTo({
      url: '/pages/news/chatroom/chatroom?username=' + JSON.stringify(nameList),
    })
  },
  /**跳转购物车 */
  toCarts() {
    wx.navigateTo({
      url: '/mall/buyCar/buyCar',
    })
  },
  /** 保存到相册 */
  saveImage() {
    wx.showLoading({
      title: '保存中...',
      mask: true,
    })
    wx.downloadFile({
      url: this.data.info.shop_info.qrCode.url,
      success: (res) => {
        if (res.statusCode === 200) {
          const img = res.tempFilePath
          wx.saveImageToPhotosAlbum({
            filePath: img,
            success: () => {
              wx.hideLoading()
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000,
              })
              this.cancelQrCode()
            },
            fail: () => {
              wx.hideLoading()
              wx.showToast({
                title: '保存失败',
                icon: 'success',
                duration: 2000,
              })
            },
          })
        }
      },
    })
  },
  /** 打开图片 */
  openQrCode() {
    this.setData({
      qrCodeShow: true,
    })
  },
  /** 关闭 */
  cancelQrCode() {
    this.setData({
      qrCodeShow: false,
    })
  },
  /** 举报商品 */
  report() {
    const {
      data: {
        info: { id },
      },
    } = this
    wx.showActionSheet({
      itemList: ['举报'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.navigateTo({
            url: `/pages/report/report?type=commodities&id=${id}`,
          })
        }
      },
    })
  },
  swiperChange(e: any) {
    const { current } = e.detail
    this.setData({ swiperIndex: current })
  },
  switchPreview(e: any) {
    const { type } = e.currentTarget.dataset
    this.setData({ previewType: type })
  },
})
